package com.neusoft.boss.common.client;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis配置
 */
@Component
public class RedisClient {
    private StringRedisTemplate redis;
//构造注入

    public RedisClient(StringRedisTemplate redis) {
        this.redis = redis;
    }


    //存入key value值
    public void setVal(String key, String val) {
        redis.opsForValue().set(key, val);
    }

    //根据key值取出值(JSON)字符串模式
    public String getVal(String key) {
        return redis.opsForValue().get(key);
    }


    public boolean setHash(

            String key, //redis的key值

            Map<String, String> value, //redis的value值

            int timeout, //超时参数

            TimeUnit unit //时间单位
    ) {
        boolean add = false;

        redis.opsForHash().putAll(key, value);//将key和value放入redis中
        add = redis.hasKey(key);//是否添加成功
        if (timeout > 0) {//设置了时间
            add = redis.expire(key, timeout, unit);//设置过期时间,判断添加结果
        }
        return add;
    }

    public String getKey(String key, String field) {
        Object val = redis.opsForHash().get(key, field);
        return (String) val;
    }
}
